using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.WorkOrders.Queries;

/// <summary>
/// 工单分页查询命令。
/// </summary>
public sealed record GetWorkOrderListWithPagedQuery(
    string? Wo,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<ProdWorkOrderDto>>>;

internal sealed class GetWorkOrderListWithPagedQueryHandler(IRepository<ProdWorkOrder> repo) : IRequestHandler<GetWorkOrderListWithPagedQuery, IResult<PagedList<ProdWorkOrderDto>>>
{
    public async Task<IResult<PagedList<ProdWorkOrderDto>>> Handle(GetWorkOrderListWithPagedQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .Includes(m => m.Product)
            .Includes(m => m.Line)
            .WhereIF(!string.IsNullOrWhiteSpace(request.Wo), m => m.Wo.Contains(request.Wo!))
            .OrderByDescending(m => m.CreatedTime)
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<ProdWorkOrderDto>>());
    }
}
